#include "WherePart.h"
#include "Helper.h"
#include "VarcharCell.h"
#include "IntCell.h"
#include "NullCell.h"

WherePart::WherePart()
{
}


WherePart::~WherePart()
{
}

void WherePart::selectRows(const string &str, Table* table)
{
	string column;
	string s_operator;
	string data;
	unsigned int i=0;
	//get the column name
	while(str[i] != EQUAL && str[i] != LARGER)
	{
		column +=str[i];
		++i;
	}
	//get operator string of the where part
	while(true)
	{
		if(str[i] == EQUAL || str[i] == LARGER)
		{
			while(str[i] == EQUAL || str[i] == LARGER)
			{
				s_operator += str[i];
				++i;
			}
		}
		else
		{
			++i;
			if(i>str.length())
			{
				cout << "No operator found\n";
				return;
			}
			continue;
		}
		break;
	}
	//get the data on the right side of the operator
	for(i;i<str.length();i++)
	{
		//get a varchar data with double quote
		if(str[i] == '\"')
		{
			++i;
			while(str[i]!= '\"')
			{
				data += str[i];
				++i;
			}

		}
		//if no double quote get an int data
		//with assumtion that followed the operator is just the data
		else
			data += str[i];
	}
	int index= table->getColumnIndex(column);
	vector<int> types= table->getTypes();
	vector<Row *> rowsOfTable= table->getRows();
	vector<Cell *> cellsOfRow;
	for(unsigned int i=0;i<rowsOfTable.size();i++)
	{
		cellsOfRow= rowsOfTable[i]->getCells();
		if(compareCell(s_operator, data, cellsOfRow[index], types[index]))
		{
			selectedRows.push_back(rowsOfTable[i]);
			selectedRowsIndex.push_back(i);
		}
	}

}


bool WherePart::compareCell(const string &s_operator, const string &data, Cell* p_cell, int type)
{
	if(type == VARCHAR)
	{
		VarcharCell* vCell= dynamic_cast<VarcharCell *>(p_cell);
		if(!vCell)
		{
			//this varcharcell is null so return false
			return false;
		}
		string value= vCell->getData();
		if(s_operator == "=")
		{
			if(helper->toUpperString(value) == helper->toUpperString(data))
				return true;
			else
				return false;
		}
		else if(s_operator == ">")
		{
			if(helper->toUpperString(value) > helper->toUpperString(data))
				return true;
			else
				return false;
		}
		else
		{
			cout << "Wrong operator\n";
			return false;
		}
	}
	else if(type == INT)
	{
		IntCell* iCell= dynamic_cast<IntCell *>(p_cell);
		if(!iCell)
		{
			return false;
		}
		int value= iCell->getData();
		int idata= helper->StringtoInt(data);
		if(s_operator == "=")
		{
			if(value == idata)
				return true;
			else
				return false;
		}
		else if(s_operator == ">")
		{
			if(value>idata)
				return true;
			else
				return false;
		}
		else
		{
			cout << "Wrong operator\n";
			return false;
		}
	}
	return true;
}

vector<Row *> WherePart::getSelectedRows()
{
	return selectedRows;
}

vector<int> WherePart::getSelectedRowsIndex()
{
	return selectedRowsIndex;
}
